package com.kly.cashmall.framework.module;

import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.kly.cashmall.framework.base.AbstractPresenterFragment;


public abstract class BaseFragment extends AbstractPresenterFragment {
  private boolean isVisibleToUser = true;

  private boolean isViewPrepared = false;

  @Override public void setArguments(Bundle args) {
    super.setArguments(args);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
      Bundle savedInstanceState) {
    View rootView;
    if ((rootView = getView()) == null) {
      rootView = inflater.inflate(getContentViewId(), viewGroup, false);
    }
    return rootView;
  }

  @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setView(savedInstanceState);
    isViewPrepared = true;

    if (!inFragmentPageAdapter() || isVisibleToUser) {
      pageLoadData();
    }
  }

  @Override public void setUserVisibleHint(boolean isVisibleToUser) {
    this.isVisibleToUser = isVisibleToUser;
    super.setUserVisibleHint(isVisibleToUser);

    if (inFragmentPageAdapter() && isVisibleToUser) {
      pageLoadData();
    }
  }

  @Override public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if (!hidden) {
      onPageInTop();
    }
  }

  private void pageLoadData() {
    if (isViewPrepared) {
      isViewPrepared = false;
      loadData();
      onPageInTop();
    }
  }

  /**
   * Fragment位于栈顶
   */
  protected void onPageInTop() {
    Log.i("BaseFragment", getClass().getSimpleName() + " onPageInTop");
  }

  private SparseArray<Fragment> fragmentSparseArray = new SparseArray<>();

  /**
   * 是否存在于ViewPager中
   * 返回true则根据UserVisibleHint的值懒加载
   */
  protected boolean inFragmentPageAdapter() {
    return false;
  }

  /***
   * 获取当前界面的XML layout Id
   */
  protected abstract int getContentViewId();

  /**
   * 数据，界面处理
   */
  protected abstract void setView(@Nullable Bundle savedInstanceState);

  protected abstract void loadData();

  public void onRestart() {
  }

  @Override public void onPause() {
    super.onPause();
  }

  private boolean isFirstResume = true;

  @Override public void onResume() {
    super.onResume();
    if (!isFirstResume) {
      onRestart();
    }
    isFirstResume = false;
  }

  @Override public void onDestroy() {
    fragmentSparseArray.clear();
    super.onDestroy();
  }

}
